﻿
using Xacml.Core.Interfaces;
using Xacml.Core.Runtime.Functions;

namespace Xacml.Core.Runtime.DataTypes
{
  public class Rfc822Name : IDataType
  {
    private string _fullName;
    private string _domainPart;
    private string _localPart;

    public IFunction EqualFunction
    {
      get
      {
        return (IFunction) new Rfc822NameEqual();
      }
    }

    public IFunction IsInFunction
    {
      get
      {
        return (IFunction) new Rfc822NameIsIn();
      }
    }

    public IFunction SubsetFunction
    {
      get
      {
        return (IFunction) new Rfc822NameSubset();
      }
    }

    public string DataTypeName
    {
      get
      {
        return "urn:oasis:names:tc:xacml:1.0:data-type:rfc822Name";
      }
    }

    internal Rfc822Name()
    {
    }

    public Rfc822Name(string name)
    {
      int length = name.IndexOf('@');
      if (length != -1)
      {
        this._localPart = name.Substring(0, length);
        this._domainPart = name.Substring(length + 1).ToLower();
        this._fullName = this._localPart + "@" + this._domainPart;
      }
      else
      {
        this._domainPart = name.Substring(length + 1).ToLower();
        this._fullName = this._domainPart;
      }
    }

    public override int GetHashCode()
    {
      return base.GetHashCode();
    }

    public override bool Equals(object obj)
    {
      if (!(obj is Rfc822Name))
        return base.Equals(obj);
      return this._fullName == ((Rfc822Name) obj)._fullName;
    }

    public bool Matches(string compareTo)
    {
      if (compareTo.IndexOf('@') == -1)
        return this._domainPart == compareTo;
      return this._fullName == compareTo;
    }
  }
}
